package com.wowangz.cms.systemmanage.parameter.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.parameter.pojo.Parameter;
import com.wowangz.cms.systemmanage.parameter.service.ParameterService;

@Scope("prototype")
@Controller
public class ParameterController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(ParameterController.class);

	/**
	 * 点击菜单"系统参数配置"显示“系统参数配置”列表
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/parameter/parameterQueryList.web")
	public String queryParameterList(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/parameter/parameterList";
	}

	/**
	 * 打开“系统参数配置”列表加载列表数据
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/systemmanage/parameter/queryParameterListInfoDataGrid.json")
	public void queryParameterListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			ParameterService parameterService = (ParameterService) IssTransactionContainer.getInstance(ParameterService.class, false);
			long resultCount = parameterService.findResultCount(map);
			List<Parameter> resultList = parameterService.findResultList(map);
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("name", DataTypeConstant.STRING);
			dataStyle.addDepict("code", DataTypeConstant.STRING);
			dataStyle.addDepict("description", DataTypeConstant.STRING);
			dataStyle.addDepict("value", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("type", SysConstant.ParameterType.class, "getName", new Class[] { long.class });
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug(e.getMessage());
		}
	}

	/**
	 * 跳转系统参数新增页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/parameter/toAddParameter.web")
	public String toAddParameter(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/parameter/parameterAdd";
	}

	/**
	 * 新增系统参数
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/parameter/addParameter.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addParameter(HttpServletRequest request, HttpServletResponse response, Model model) {
		Parameter parameter = null;
		ParameterService parameterService = (ParameterService) IssTransactionContainer.getInstance(ParameterService.class, false);
		try {
			parameter = (Parameter) ServletUtils.getParametersToBaseEntity(request, Parameter.class);
			parameter.setInputtime(new Date());
			parameter.setInputuserid(userContext.getLoginUser().getId());
			parameter.setModifytime(new Date());
			parameter.setModifyuserid(userContext.getLoginUser().getId());
			parameter.setStatusid(SysConstant.RecordStatus.VALID);
			parameterService.addParameter(parameter);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			getUserContext().setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		}
		return "/WEB-INF/jsp/systemmanage/parameter/parameterList";
	}

	/**
	 * 验证系统参数（不允许重复的系统参数编码）
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/parameter/validationParameter.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validationParameter(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		Parameter parameter = null;
		ParameterService parameterService = (ParameterService) IssTransactionContainer.getInstance(ParameterService.class, false);
		try {
			HashMap<String, Object> map = new HashMap<String, Object>();
			parameter = (Parameter) ServletUtils.getParametersToBaseEntity(request, Parameter.class);

			map.put("statusid", SysConstant.RecordStatus.VALID);
			if (null != parameter.getId()) {
				map.put("id", parameter.getId());
			}
			map.put("code", parameter.getCode());
			if (!parameterService.validationParameter(map)) {
				getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.parameter.parametercodeexsit"));
			}
			// 如果是选择值 不能为空
			if (parameter.getType() == SysConstant.ParameterType.SELECT) {
				if (!StringUtils.isNotEmpty(parameter.getSelectvaluelist())) {
					getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.parameter.selectvalueexsit"));
				}
			}
			map.remove("code");
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, getUserContext()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 进入系统参数修改
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/systemmanage/parameter/toUpdateParameter.web")
	public String toUpdateParameter(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String id = getRequest().getParameter("id");
			ParameterService parameterService = (ParameterService) IssTransactionContainer.getInstance(ParameterService.class, false);
			Parameter parameter = parameterService.findParameterById(id);
			if (parameter != null) {
				parameter.setTypename(SysConstant.ParameterType.getName(parameter.getType()));
			}
			if (parameter.getSelectvaluelist() != null && !"".equals(parameter.getSelectvaluelist())) {
				String[] list = parameter.getSelectvaluelist().split(";");
				model.addAttribute("list", list);
			} else {
				model.addAttribute("list", new ArrayList());
			}
			model.addAttribute("parameter", parameter);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/parameter/parameterUpdate";
	}

	/**
	 * 修改系统参数
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/parameter/updateParameter.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateParameter(HttpServletRequest request, HttpServletResponse response, Model model) {
		ParameterService parameterService = (ParameterService) IssTransactionContainer.getInstance(ParameterService.class, false);
		String id = request.getParameter("id");
		try {
			if (StringUtils.isNotEmpty(id)) {
				Parameter parameter = (Parameter) ServletUtils.getParametersToBaseEntity(request, Parameter.class);
				parameter.setModifytime(new Date());
				String value = request.getParameter("value");
				parameter.setValue(value);
				parameter.setId(Long.valueOf(id));
				parameter.setModifyuserid(userContext.getLoginUser().getId());
				parameterService.updateParameter(parameter);
				getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
				getUserContext().setCloseWindow(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		}
		return "/WEB-INF/jsp/systemmanage/parameter/parameterList";
	}

	/**
	 * 进入系统参数查看
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/parameter/toViewParameter.web")
	public String toViewParameter(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String id = getRequest().getParameter("id");
			ParameterService parameterService = (ParameterService) IssTransactionContainer.getInstance(ParameterService.class, false);
			Parameter parameter = parameterService.findParameterById(id);
			if(parameter!=null){
				parameter.setTypename(SysConstant.ParameterType.getName(parameter.getType()));
			}
			model.addAttribute("parameter", parameter);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/parameter/parameterView";
	}
}
